<template>
  <div style="width: 100%;">
    <el-card shadow="hover">
      <OaFileTable :header="header" :tableData="fileDetails" @open-file-dialog="openFileDialog" />
    </el-card>
    <!-- 文件选择弹框 -->
    <FileDialog ref="fileDialogRef" :folderDisabled="folderDisabled" v-model="modelValue" @success="success" @cancel="cancel" />
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, defineProps ,defineEmits} from 'vue'
import OaFileTable from '@/components/Oa/OaFileTable.vue'
import FileDialog from '@/views/infra/file/FileDialog.vue'
import { getFileListByIds } from '@/api/infra/file'

// 接收外部传入的文件 ID 和文件详情
const props = defineProps({
  header: {
    type: Boolean,
    default: true // 是否显示表格头部
  },
  folderDisabled: Boolean,
  initialFileIds: {
    type: [Array, String],
    default: () => []
  }
})
const emit = defineEmits(['fileSelectSuccess'])
// 文件选择相关
const fileDialogRef = ref()
const modelValue = ref<string[]>([]) // 绑定到 FileDialog 的文件 ID
const selectedFileIds = ref<string[]>([])
const fileDetails = ref<{ id: string; title: string; type: string; createTime: string; creator: string }[]>([])
console.log('initialFileIds', props.folderDisabled)
// 打开文件选择弹框
const openFileDialog = () => {
  modelValue.value = selectedFileIds.value // 初始化已选择的文件 ID
  fileDialogRef.value.open()
}

// 获取文件详情
const getFileListByIdsApi = async (ids: string[]) => {
  // 实际项目应调用后端接口，这里 mock 返回
  return getFileListByIds(ids)
}
const success = (fileIds: string[]) => {
  selectedFileIds.value = fileIds
  emit('fileSelectSuccess', fileIds)
}
const cancel = () => {
  // 取消操作时可以清空已选择的文件 ID
  // selectedFileIds.value = []
}
// 监听文件 ID 的变化，更新文件详情
watch(
  () => props.initialFileIds,
  (newVal) => {
    if (typeof newVal === 'string') {
      selectedFileIds.value = newVal ? newVal.split(',') : []
    } else if (Array.isArray(newVal)) {
      selectedFileIds.value = newVal
    } else {
      selectedFileIds.value = []
    }
  },
  { immediate: true }
)
watch(
  selectedFileIds,
  async (newVal) => {
    if (!newVal || newVal.length === 0) {
      fileDetails.value = []
      return
    }
    if(newVal.length > 0){
      fileDetails.value = await getFileListByIdsApi(newVal)
    }
  },
  { immediate: true }
)
</script>
<style scoped>
/* 可根据需求添加样式 */
</style>